import sys
import jc_pty as pty
import os

columns, lines = os.get_terminal_size()


def mqtt_out(s, end='\n'):
    pty.input_into_pty(s+end)

while 1:
    print('[starting pty]')
    pty.start_pty(lambda s:print(s,end=''))
    mqtt_out(f'stty rows {lines-1} cols {columns}')
    mqtt_out(f'export TERM=xterm-256color')

    while 1:
        if pty._check_subprocess():
            break
        try:
            cmd = input() + '\n'
        except KeyboardInterrupt:
            sys.stdout.write(f'\x1b[{lines}f')
            s = input('[wsadeqbxonW-]')
            repeat = 1
            if len(s)>1:
                try:
                    repeat = int(s[1:].strip())
                except:
                    pass
            
            if not s:
                cmd = '\x03'
            elif s[0] == 'w':
                cmd = '\x1b[A'
            elif s[0] == 's':
                cmd = '\x1b[B'
            elif s[0] == 'a':
                cmd = '\x1b[D'
            elif s[0] == 'd':
                cmd = '\x1b[C'
            elif s == 'e':
                cmd = '\x1b\x1b'
            elif s == 'q':
                break
            elif s[0]=='x':
                cmd = '\x18'
            elif s[0]=='o':
                cmd = '\x0f'
            elif s[0]=='W':
                cmd = '\x17'
            elif s[0] == 'b':
                cmd = '\x08'
            elif s[0] == 'n':
                cmd = '\r\n'
            elif s[0] == '-':
                cmd = s[1:]
            else:
                cmd = s
            cmd = cmd * repeat
        except EOFError:
            s=input('[quit y/n]')
            if s=='y' or s=='Y' or s=='yes' or s=='YES' or s =='q': 
                break
            cmd = '\x04'
        mqtt_out(cmd, end='')
